<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">
      插入图片
    </el-button>
    <el-dialog :visible.sync="dialogVisible">
      <el-upload
        :multiple="true"
        :data="QiniuData"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        class="editor-slide-upload"
        action="https://upload-z1.qiniup.com"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          点击上传
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        确定
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'
import api from '@/fetch/url.js';
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  
  data() {
    return {
      QiniuData: {
          key: "", //图片名字处理
          token: "" //七牛云token
      },
      qiniuaddr: "https://cdn.yueyangshuyuan.com/", // 七牛云的图片外链地址 你的七牛云里配置有
      bucket:'sojour',
      dialogVisible: false,
      listObj: {},
      fileList: []
    }
  },
  created(){
        api.upToken({
            accessKey:'i5zelMCxFeu45ob45iFOBdWPvOTraza1wXvWAg73',
            secretKey:'leGRrXl_Kr5aXuxKQ7laa6jrZvzxgs6LGeOCfrxW',
            bucket:this.bucket
        }).then(json=>{
            this.QiniuData.token = json;
        })

     
    },

  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message('图片还未上传完成，请稍等!')
        return
      }
      this.$emit('successCBK', arr)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      // console.log(response,this.listObj,8888888888);
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          console.log(this.listObj[objKeyArr[i]].url,"url");
          this.listObj[objKeyArr[i]].url = this.qiniuaddr+response.key;
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    //以下是时间戳函数
    getDate(){
        var myDate = new Date();
        //获取当前年
        var year = myDate.getFullYear();
        //获取当前月
        var month = myDate.getMonth() + 1;
        //获取当前日
        var date = myDate.getDate();
        var h = myDate.getHours(); //获取当前小时数(0-23)
        var m = myDate.getMinutes(); //获取当前分钟数(0-59)
        var s = myDate.getSeconds();
        //获取当前时间
        var now = year + '_' + this.conver(month) + "_" + this.conver(date) + "_" + this.conver(h) + '_' + this.conver(m) + "_" + this.conver(s);
        return now;
    },
    conver(s) {
            return s < 10 ? '0' + s : s;
    },
    beforeUpload(file) {
        const isPNG = file.type === "image/png";
        const isJPEG = file.type === "image/jpeg";
        const isJPG = file.type === "image/jpg";
        const isLt2M = file.size / 1024 / 1024 < 1;
        if (!isPNG && !isJPEG && !isJPG) {
            this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
            return false;
        }
        if (!isLt2M) {
            this.$message.error("上传头像图片大小不能超过 1MB!");
            return false;
        }
      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid;
      this.QiniuData.key = `yuyang_${this.getDate()}${fileName}`;
      // console.log(this.QiniuData.key,11111111111);
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function() {
          _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
        }
        resolve(true)
      })
     
    }
  }
}
</script>
<style>
.mce-i-image,#mceu_74,#mceu_22 {
  display: none !important;
}
.mce-panel {
  border-width:0 !important;
  border: 1px solid #DCDFE6 !important;
  box-shadow:none !important;
}
.mce-menubar,.mce-top-part::before,.mce-first,.mce-toolbar-grp,.mce-top-part::before {
  border:none !important;
  border-width:none !important;
  box-shadow:none !important;
}
.mce-statusbar {
  border:none !important;
}
.mce-edit-area {
  border-left:none !important;
  border-right:none !important;
}
</style>
<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}

</style>
